<?php

namespace app\common\model;

use think\Db;
use think\Model;

class DeliveryTask extends Model
{
    // 表名
    protected $name = 'delivery_task';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    
    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
        'next_time_text',
	    'status_text'
    ];
    

    const STATUS_ING = 0;
    const STATUS_F = 1;
    
	public static $statusList = [
		self::STATUS_ING => '发货中',
		self::STATUS_F => '已完成'
	];
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? $value : $data['status'];
		$list = self::$statusList;
		return isset($list[$value]) ? $list[$value] : '';
	}


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getNextTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['next_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setNextTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
	
	/**
	 * 添加发货商品发货任务
	 * @param $orderId
	 * @param $userId
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function createTask($orderId,  $userId) {
    	$goods = Db::name('orderGoods')
		    ->where(['order_id' => $orderId, 'goods_type' => Goods::GOODS_TYPE_2])
		    ->find();
    	if($goods) {
    		$res = $this->isUpdate(false)
			    ->save([
				    'user_id' => $userId,
				    'order_id' => $orderId,
				    'order_goods_id' => $goods['id'],
				    'need_number' => $goods['send_number'],
				    'days' => $goods['send_day']
			    ]);
    		if(!$res) {
    			return false;
		    }
	    }
	    
	    return true;
    }

    
    public function user(){
    	return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
    }
    
    public function orderGoods(){
    	return $this->belongsTo('orderGoods', 'order_goods_id', 'id', '', 'left')->setEagerlyType(0);
    }
}
